package cn.iocoder.yudao.module.product.favorite.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.interest.service.AppInterestBaseService;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.product.spu.ProductSpuApi;
import cn.iocoder.yudao.module.api.product.spu.dto.ProductSpuRespDTO;
import cn.iocoder.yudao.module.product.favorite.dal.dataobject.ProductFavoriteDO;
import cn.iocoder.yudao.module.product.favorite.dal.mysql.ProductFavoriteMapper;
import cn.iocoder.yudao.module.product.favorite.vo.AppProductFavoriteVO;
import cn.iocoder.yudao.module.product.spu.vo.AppProductSpuSimpleRespVO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

/**
 * 产品收藏 Service 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class AppProductFavoriteServiceImpl extends AppInterestBaseService<AppProductSpuSimpleRespVO, ProductFavoriteDO, AppProductFavoriteVO> implements AppProductFavoriteService {
    @Resource
    private ProductFavoriteMapper productFavoriteMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖报错
    private ProductSpuApi productSpuApi;

    @Override
    protected ProductFavoriteMapper getInjectedMapper() {
        return productFavoriteMapper;
    }

    @Override
    public AppProductSpuSimpleRespVO validateSnapshotExists(Long bizId) {
        ProductSpuRespDTO respDTO = productSpuApi.validateSpu(bizId);
        return BeanUtils.toBean(respDTO, AppProductSpuSimpleRespVO.class);
    }

    @Override
    public PageResult<AppProductFavoriteVO> getPage(Integer current, Integer size, Long userId) {
        CoreQueryWrapper<ProductFavoriteDO> wrapper = new CoreQueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("recycled", false);
        PageResult<ProductFavoriteDO> page = productFavoriteMapper.selectPage(current, size, wrapper);
        if (CollUtil.isEmpty(page.getList())) {
            return PageResult.empty();
        }
        return new PageResult<>(page.getList().stream().map(this::convertToViewObject).toList(), page.getTotal());
    }

}
